package com.bangcommunity.bbframe.media.video;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;

/**
 * @author tanghc
 * @date 18/6/27
 */
public class JavaCvUtil {
    public static VedioInfo snapshot(InputStream vedioInputStream) throws Exception {
        return snapshot(new FFmpegFrameGrabber(vedioInputStream));
    }
    public static VedioInfo snapshot(File vedioFile) throws Exception {
        return snapshot(FFmpegFrameGrabber.createDefault(vedioFile));
    }
    public static VedioInfo snapshot(String vedioFilePath) throws Exception {
        return snapshot(FFmpegFrameGrabber.createDefault(vedioFilePath));
    }
    public static VedioInfo snapshot(FFmpegFrameGrabber ff) throws Exception {
        ff.start();
        Frame f = ff.grabImage();
        if (null == f || null == f.image) {
            return null;
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bi = converter.getBufferedImage(f);
        VedioInfo vedioInfo = new VedioInfo();
        vedioInfo.setSnapshot(bi);
        vedioInfo.setHeight(ff.getImageHeight());
        vedioInfo.setWidth(ff.getImageWidth());
        vedioInfo.setLength(ff.getLengthInTime());
        ff.stop();
        return vedioInfo;
    }
}
